import constant from "@/static/utils/constant.js";
import address from "@/static/utils/address.js";
import store from '@/store'
const utils = {};

/**
 * 返回当前时间戳。格式如下
 * @returns yyyymmddhhmiss
 */
utils.getTimeStamp = () => {
	var date = new Date();
	return date.getFullYear().toString() +
		(date.getMonth() + 1).toString().padStart(2, 0) +
		(date.getDate()).toString().padStart(2, 0) +
		(date.getHours()).toString().padStart(2, 0) +
		(date.getMinutes()).toString().padStart(2, 0) +
		(date.getSeconds()).toString().padStart(2, 0);
};

/**
 * 返回时间字符串
 * type:
 * 		1、年，最终返回yyyy
 * 		2、月，最终返回yyyy-mm
 * 		3、日，最终返回yyyy-mm-dd
 * diff: 相对参数d的偏移量
 * 		type == 1时，偏移量为年
 * 		type == 2时，偏移量为月
 * 		type == 3时，偏移量为天
 * d: Date对象
 */
utils.getDateStr = (type = constant.dateType.day.val, diff = 0, d = new Date()) => {
	if (type == constant.dateType.year.val) {
		d = new Date(d.setFullYear(d.getFullYear() + diff));
		return d.getFullYear().toString();
	} else if (type == constant.dateType.month.val) {
		d = new Date(d.setMonth(d.getMonth() + diff));
		return `${d.getFullYear().toString()}-${(d.getMonth() + 1).toString().padStart(2, 0)}`;
	} else if (type == constant.dateType.day.val) {
		d = new Date(d.setDate(d.getDate() + diff));
		return `${d.getFullYear().toString()}-${(d.getMonth() + 1).toString().padStart(2, 0)}-${(d.getDate()).toString().padStart(2, 0)}`;
	}
	return "";
};

/**
 * 金额千分位加逗号，保留2位小数，不足补零，否则四舍五入
 * 参数说明：
 * num：要格式化的数字 string或者number
 * decimals：保留几位小数
 * thousandsSep：千分位符号
 return 金额格式的字符串,如'1,234,567.45'
 */
utils.fmoney = (num, decimals = 2, thousandsSep = ',') => {
	if (isNaN(num) || num == 0) {
		num = '0.00'
	}
	let prec = !isFinite(+decimals) ? 0 : Math.abs(decimals) // 保留的位数一定是有限位数的正整数
	let sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
	let s = num.toString().replace(/,/g, '') // 字符串，将，变成'';
	let p = parseFloat(s) // 解析一个字符串，并返回一个浮点数
	let n = isNaN(p) ? 1 : p
	let formatNum = n.toFixed(prec).toString().replace(/(\d)(?=(\d{3})+\.)/g, function($0, $1) {
		return $1 + sep
	})
	return num ? formatNum : num
}

/**
 * 空判断
 */
utils.isNull = (obj) => {
	return (
		obj === null ||
		obj === undefined ||
		obj === "" ||
		obj === "null" ||
		obj === "undefined"
	);
}

/**
 * 获取某个常量项的信息(通过常量类型和常量值)
 */
utils.getConstantItemByVal = (typeName, val) => {
	let finded = Object.values(constant[typeName]).find(item => item.val == val)
	return finded ? finded : {};
}

/**
 * 获取某个常量类型的信息数组
 */
utils.getConstOptions = (typeName) => {
	return Object.values(constant[typeName]).filter((item) => {
		return item.show == null || item.show == undefined || item.show == true;
	});
}

/**
 * 获取省列表
 */
utils.getProvinces = () => {
	return address.map(p => {
		return {
			id: p.id,
			name: p.name,
		}
	});
}

/**
 * 获取市列表
 */
utils.getCities = (provinceId) => {
	let rst = [];
	let finded = address.find(p => {
		return p.id == provinceId
	});
	if (finded) {
		rst = finded.children.map((c) => {
			return {
				id: c.id,
				name: c.name,
			}
		});
	}
	return rst;
}

/**
 * 获取当前页带参数的url
 */
utils.getCurrentPageUrlWithArgs = () => {
	let pages = getCurrentPages() // 获取加载的页面
	let currentPage = pages[pages.length - 1] // 获取当前页面的对象
	let url = currentPage.route // 当前页面url
	let options = currentPage.options // 如果要获取url中所带的参数可以查看options

	// 拼接url的参数
	let urlWithArgs = url + `?`
	for (let key in options) {
		let value = options[key]
		urlWithArgs += key + `=` + value + `&`
	}
	urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)

	return `/${urlWithArgs}`
}

/**
 * 强制刷新当前页面
 */
utils.pageReload = () => {
	const pages = getCurrentPages()
	const curPage = pages[pages.length - 1]
	curPage.onLoad(curPage.options)
	curPage.onShow()
	curPage.onReady()
}

/**
 * 清除缓存
 */
utils.clearStorage = () => {
	uni.removeStorageSync("token");
	uni.removeStorageSync("userInfo");
	uni.removeStorageSync("inviteProj");
	// uni.clearStorageSync();
}

/**
 * 校验手机号码
 */
utils.checkMobile = (v) => {
	return /^1[3-9]\d{9}$/.test(v);
}

/**
 * 校验银行卡
 */
utils.checkBankCardNumber = (v) => {
	const regex = /^[1-9]\d{9,29}$/;
    if (regex.test(v)) {
        console.log('银行卡号格式正确');
        return true;
    } else {
        console.log('银行卡号格式错误');
        return false;
    }
}

/**
 * 银行卡号脱敏
 */
utils.maskBankCardNumber = (v) => {
    if (!v) {
        return '';
    }
    // 去除银行卡号中的空格和其他非数字字符
    const cleanCardNumber = v.replace(/\D/g, '');
    if (cleanCardNumber.length <= 8) {
        return cleanCardNumber;
    }
    const start = cleanCardNumber.slice(0, 4);
    const end = cleanCardNumber.slice(-4);
    // const maskLength = cleanCardNumber.length - 8;
    // const mask = '*'.repeat(maskLength);
    const mask = '*'.repeat(6);
    return start + mask + end;
}

/**
 * 法大大合同地址格式化
 */
utils.fmtFDDUrl = (v) => {
    if (!v) {
        return '';
    }
	if(v.indexOf('textapi08') > -1){
		return v.replaceAll('textapi08', 'textapi12');
	}
	if(v.indexOf('textapi.fadada') > -1){
		return v.replaceAll('textapi.fadada', 'textapi12.fadada');
	}
	return v;
}

/**
 * 等待N毫秒
 */
utils.waitByMs = (ms = 1000) => {
	return new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve(ms)
		}, ms)
	})
}

/**
 * 下载(打开)文件
 * url: 文件地址
 * noInitPage: 打开文档后会拉起手机里的app来预览文件，预览完毕回到小程序时，会触发onshow，noInitPage字段则控制是否需要触发onshow
 */
utils.handleDownload = (url, noInitPage) => {
	uni.showLoading({
		title: '加载中',
		mask: true,
	})
	uni.downloadFile({
		url: url,
		success(res) {
			uni.saveFile({
				tempFilePath: res.tempFilePath,
				success: (res) => {
					console.log(res.savedFilePath);
					// uni.showToast({
					// 	icon: 'success',
					// 	mask: true,
					// 	title: '文件已保存!',
					// 	duration: 3000,
					// });
					if (noInitPage) {
						uni.setStorageSync(noInitPage, "1");
					}
					uni.openDocument({
						// fileType: 'docx',
						filePath: res.savedFilePath,
						success: function(res) {
							console.log('打开文档成功');
						},
					});
				}
			});
		},
		fail: (err) => {},
		complete: (res) => {
			uni.hideLoading();
		},
	});
}

/**
 * 跳转第三方小程序
 */
utils.navigateToMiniProgram = (targetUrl) => {
	wx.navigateToMiniProgram({
		appId: 'wxc46c6d2eed27ca0a', // 通联小程序 appId
		path: 'pages/merchantAddress/merchantAddress', // 通联小程序页面路径
		extraData: {
			targetUrl: targetUrl // 商户拼接的请求报文
		},
		envVersion: 'release', //develop 开发版 trial 体验版 release 正式版
		success(res) {
			// 打开成功
			console.log(res)
		}
	})
}

export default utils;